package com.freaky.paomian;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class PaomianActivity extends Activity
{
	// 时间转换到毫秒
	private static long MIL_DAY = 1000 * 24 * 60 * 60;
	private static long MIL_HOUR = 1000 * 60 * 60;
	private static long MIL_MINUTE = 1000 * 60;
	private static long MIL_SECOND = 1000;
	private static int SEC_MINUTE = 60;
	private AdvancedCountDownTimer cdTimer;
	private TextView txtView;
	private SeekBar setTimeBar; // 建立一个设置时间的滚动条
	private ProgressBar pgbLeftTime;// 建立有一个进度条
	private TextView setTimeView; // 显示已经设置的时间
	private TextView tsetTimeView;// 显示设置时间的差值
	private int barSeconds;// 储存进度条上所表示的时间
	private int barSeconds2;// 第二次设置进度条时设置的时间
	private int tbarSeconds;// 进度条上面相邻两次设置的时间的差值
	private long leftSeconds;// 倒计时已经计数的时间
	private boolean setted = false; // 是否已经在滚动条上设定时间
	private boolean setted2 = false;// 是否在滚动条上多次设置时间
	private boolean progressChanged = false;// 是否拖动了滚动条
	private boolean running = true;// 倒计时是否在工作
	private boolean pgbLeftTimeMove = false;// 检查进度条是否在移动，否则在移动的时候会误判为长按
	private boolean cdTimerPause = false;// 检查cdtimer是否处于暂停状态
	// 创建一个声音流
	private SoundPool sp;
	// 设置声音
	private int soundDing;
	private int soundDang;
	// 声音播放循环次数
	private static int soundLoop = 0;
	// 声音播放速度
	private static int soundSpeed = 1;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 程序初始化
		appInitialize();
		// 监听time设置的改变
		setTimeBar.setOnSeekBarChangeListener(setTimeBarL);
		// 初始化屏幕大小
		DisplayMetrics dmDisplayMetrics = getResources().getDisplayMetrics();
		final int screenWidth = dmDisplayMetrics.widthPixels;
		final int screenHeight = dmDisplayMetrics.heightPixels - 120;
		// 点击进度条之后暂停倒计时，再次点击恢复
		/*
		 * pgbLeftTime.setOnClickListener(new OnClickListener() {
		 * 
		 * public void onClick(View v) { // TODO Auto-generated method stub if
		 * (running) { cdTimer.pause(); txtView.setText("倒计时被暂停");
		 * running=false; }else { cdTimer.resume(); running=true; } } });
		 */
		// 长按调整时间
		pgbLeftTime.setOnLongClickListener(new OnLongClickListener()
		{

			public boolean onLongClick(View v)
			{
				if (!pgbLeftTimeMove)
				{
					pgbLeftTime.setVisibility(View.INVISIBLE);
					setTimeBar.setVisibility(View.VISIBLE);
					tsetTimeView.setVisibility(View.VISIBLE);
				}
				return false;
			}
		});
		// 拖动进度条实现取暂停计时功能
		pgbLeftTime.setOnTouchListener(new OnTouchListener()
		{
			int lastX = 0;
			int lastY = 0;

			public boolean onTouch(View v, MotionEvent event)
			{
				// TODO Auto-generated method stub
				int ea = event.getAction();
				int sl=v.getBottom()-v.getTop();
				switch (ea)
				{
				case MotionEvent.ACTION_DOWN:
					lastX = (int) event.getRawX();
					lastY = (int) event.getRawY();
					pgbLeftTimeMove = false;
					break;
				case MotionEvent.ACTION_MOVE:
					// 移动控件
					pgbLeftTimeMove = true;
					int dX = (int) event.getRawX() - lastX;
					int dY = (int) event.getRawY() - lastY;
					int l = v.getLeft();
					int b = v.getBottom() + dY;
					int r = v.getRight();
					int t = b-sl;
					v.layout(l, t, r, b);
					lastX = (int) event.getRawX();
					lastY = (int) event.getRawY();
					// 拖动进度条到底端，暂停倒计时。拖回恢复
					if (b<20)
					{
						b=screenHeight+20;
						t=b-sl;
						v.layout(l, t, r, b);
					}
					if (b > screenHeight)
					{
						cdTimer.pause();
						cdTimerPause = true;
					}
					if ((b <= screenHeight) & (cdTimerPause))
					{
						cdTimer.resume();
						cdTimerPause = false;
					}

				default:
					break;
				}
				return false;
			}
		});
	}

	private void CountDownFinished()
	{
		setted = false;
		setted2 = false;
	}

	// 播放音乐
	private void playSound(int sound)
	{
		// 播放声音
		AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
		float streamVolumnCurrent = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		float streamVolumnMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volumn = streamVolumnCurrent / streamVolumnMax;
		sp.play(sound, volumn, volumn, 1, soundLoop, soundSpeed);
	}

	/*
	 * 倒计时开始
	 */
	private void CountDownTimerStart(long setSeconds)
	{
		setSeconds = setSeconds * 1000;
		cdTimer = new AdvancedCountDownTimer(setSeconds, 1000)
		{

			@Override
			public void onTick(long millisUntilFinished, int percent)
			{
				// TODO Auto-generated method stub
				StringBuilder strShow = new StringBuilder();
				// 倒计时剩下的时间
				leftSeconds = (int) millisUntilFinished / 1000;
				// 最后10秒用声音倒计时
				if (millisUntilFinished <= 5000)
				{
					playSound(soundDang);
				}
				strShow.append("还剩");
				if (millisUntilFinished >= MIL_DAY)
				{
					strShow.append(millisUntilFinished / MIL_DAY);
					strShow.append("天");
				}
				if (millisUntilFinished >= MIL_HOUR)
				{
					strShow.append((millisUntilFinished / MIL_HOUR) % 24);
					strShow.append("小时");
				}
				if (millisUntilFinished >= MIL_MINUTE)
				{
					strShow.append((millisUntilFinished / MIL_MINUTE) % 60);
					strShow.append("分");
				}
				strShow.append((millisUntilFinished / MIL_SECOND) % 60);
				strShow.append("秒");
				txtView.setText(strShow.toString());
				// 这个进度条需要好好写一写
				pgbLeftTime.setProgress(percent);
				setTimeBar.setSecondaryProgress(6 * percent);
			}

			@Override
			public void onFinish()
			{
				// TODO Auto-generated method stub
				txtView.setText("倒计时终了");
				CountDownFinished();
				playSound(soundDing);

			}
		}.start();
	}

	// 用滚动条设置时间，滚动条监听
	private OnSeekBarChangeListener setTimeBarL = new OnSeekBarChangeListener()
	{

		public void onStopTrackingTouch(SeekBar seekBar)
		{
			// 讲滚动条显示时间赋值于倒计时时间
			if (progressChanged)
			{
				if (setted2)
				{
					barSeconds = barSeconds2;
					cdTimer.cancel();
					leftSeconds = leftSeconds + tbarSeconds;
				} else
				{
					leftSeconds = barSeconds;
				}
				CountDownTimerStart(leftSeconds);
				setted = true;
				progressChanged = false;
				pgbLeftTime.setVisibility(View.VISIBLE);
				setTimeBar.setVisibility(View.INVISIBLE);
				tsetTimeView.setVisibility(View.INVISIBLE);
				tsetTimeView.setText("请拖动滑块再次调整泡面时间");
			}
		}

		public void onStartTrackingTouch(SeekBar seekBar)
		{
			// TODO Auto-generated method stub
			// setTimeView.setText("请拖动来调节时间");
			// progressChanged=false;
		}

		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
		{
			// 调整时间的显示格式，转换成分秒显示
			String setTime = formatTimeBar(progress);
			// 检查是否已经设置了泡面时间
			progressChanged = true;
			if (!setted)
			{
				barSeconds = progress;
				setTimeView.setText("当前设置的时间为:" + setTime);
				tsetTimeView.setText("当前设置的时间为:" + setTime);
			} else
			{
				// 检查两次设置时间的差值
				barSeconds2 = progress;
				tbarSeconds = barSeconds2 - barSeconds;
				setted2 = true;
				String tsettime = formatTimeBar(tbarSeconds);
				setTimeView.setText("当前设置的泡面总时间为:" + setTime + "\n");
				String temp = null;
				if (tbarSeconds >= 0)
				{
					temp = "增加了";
				} else
				{
					temp = "减少了";
				}
				tsetTimeView.setText("泡面时间" + temp + tsettime + "\n当前设置的泡面总时间为:" + setTime + "\n");
			}

		}

		// 格式化Seekbar进度条值所表示的时间
		private String formatTimeBar(int progress)
		{
			// TODO Auto-generated method stub
			if (progress <= 0)
			{
				progress = -progress;
			}
			int minutes = progress / SEC_MINUTE;
			int seconds = progress % SEC_MINUTE;
			String formattimeString = minutes + "分" + seconds + "秒";
			return formattimeString;
		}
	};

	// 显示一个Toast

	/*
	 * 初始化变量
	 */
	private void appInitialize()
	{
		txtView = (TextView) findViewById(R.id.txtView);
		pgbLeftTime = (ProgressBar) findViewById(R.id.pgbLeftTime);
		pgbLeftTime.setVisibility(View.INVISIBLE);
		sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		setTimeBar = (SeekBar) findViewById(R.id.setTimeBar);
		setTimeView = (TextView) findViewById(R.id.setTimerView);
		tsetTimeView = (TextView) findViewById(R.id.tsetTimerView);
		// 装载声音
		soundDing = sp.load(this, R.raw.ding, 1);
		soundDang = sp.load(this, R.raw.dang, 1);
	}
}